<template>
  <div class="category-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入种类名称搜索"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增种类
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="种类名称" min-width="120" align="center" />
      <el-table-column prop="description" label="描述" min-width="200" align="center" />
      <el-table-column prop="active" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'danger'">
            {{ scope.row.active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button 
            :type="scope.row.active ? 'warning' : 'success'" 
            link 
            @click="handleToggleStatus(scope.row)">
            {{ scope.row.active ? '禁用' : '启用' }}
          </el-button>
          <el-popconfirm
            title="确定删除该种类吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增种类' : '编辑种类'"
      width="500px"
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入种类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入种类描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.active" :label="true">启用</el-radio>
          <el-radio v-model="formData.active" :label="false">禁用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get } from '@/api/api'
import axios from 'axios'

// 创建API客户端实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8001',
  timeout: 10000
})

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  name: '',
  description: '',
  active: true
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入种类名称', trigger: 'blur' }]
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await get('/api/categories')
    console.log('种类列表数据:', res)
    if (res && Array.isArray(res)) {
      // 简单的前端分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      const filteredData = searchText.value 
        ? res.filter(item => item.name && item.name.includes(searchText.value))
        : res
      tableData.value = filteredData.slice(startIndex, endIndex)
      total.value = filteredData.length
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    description: row.description,
    active: row.active
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    const res = await apiClient.put(`/api/categories/${row.id}/toggle-status`)
    if (res.status === 200) {
      ElMessage.success('状态切换成功')
      fetchData()
    }
  } catch (error) {
    console.error('状态切换失败:', error)
    ElMessage.error('状态切换失败')
  }
}

// 删除
const handleDelete = async (id) => {
  try {
    const res = await apiClient.delete(`/api/categories/${id}`)
    if (res.status === 204 || res.status === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const submitData = {
          name: formData.name,
          description: formData.description,
          active: formData.active
        }

        let res
        if (dialogType.value === 'add') {
          res = await apiClient.post('/api/categories', submitData)
        } else {
          res = await apiClient.put(`/api/categories/${formData.id}`, submitData)
        }
        
        if (res.status === 200 || res.status === 201) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    name: '',
    description: '',
    active: true
  })
}

// 格式化时间
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
